package cn.org.mrliu.ssm.job;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * TestJob
 * 
 * @author MrLiu
 *
 */
public class TestJob {
	private static final Logger log = LoggerFactory.getLogger(TestJob.class);

	public void work() {
		log.debug("TestJob work");
		try {
			// 密码后面不能有空格
			String cmd = "mysqldump -u root -proot ssm";
			System.out.println(cmd);
			Runtime runtime = Runtime.getRuntime();
			Process process = runtime.exec(cmd);
			// 得到输入流,写成.sql文件
			InputStream inputStream = process.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
			BufferedReader reader = new BufferedReader(inputStreamReader);

			Date date = new Date();
			// 备份目录名称
			String dirName = new SimpleDateFormat("yyyy-MM").format(date);
			// SQL文件名称
			String fileName = new SimpleDateFormat("yyyy-MM-dd-HHmmss").format(date);
			fileName = "db-" + fileName + ".sql";

			File file = new File("D:\\back\\" + dirName + "\\" + fileName);
			System.out.println(file);
			file.getParentFile().mkdirs();

			PrintWriter writer = new PrintWriter(file);
			String line = null;
			while ((line = reader.readLine()) != null) {
				writer.println(line);
			}
			writer.flush();
			writer.close();

			reader.close();
			inputStreamReader.close();
			inputStream.close();
			System.out.println("备份成功");
			System.out.println(file);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
